package rainy.file.synchronization.server.commond.exec;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;

import rainy.file.synchronization.client.file.traverse.FileHasher;
import rainy.file.synchronization.client.file.traverse.FileStructure;
import rainy.file.synchronization.config.RainyRunTime;
import rainy.file.synchronization.log.RainnyLogger;
import rainy.file.synchronization.server.commond.Command;
import rainy.file.synchronization.server.commond.CommondExecutor;

public class HealthCheckCommandExecutor implements CommondExecutor<String> {

	private String folder = RainyRunTime.getPropDefine("rainy.master.target.folder");

	public String supportedCommond() {
		return RainyRunTime.COMMOND_HEALTH_CHECK;
	}

	public void executeCommand(Command<String> command) {
		String content = command.getFullContent();
		RainnyLogger.info(content);
		String result = content.substring(content.indexOf("#") + 1);
		FileStructure fst = JSON.parseObject(result, FileStructure.class);
		List<FileStructure> remainedFiles = new ArrayList<>();
		checkMissedFiles(fst, remainedFiles);
		RainnyLogger.info("Files need to be copy manually : " + remainedFiles.toString());

	}

	public void checkMissedFiles(FileStructure fst, List<FileStructure> list) {
		if (list == null) {
			list = new ArrayList<>();
		}
		File file = new File(folder + fst.getFilePath());
		if (file.exists()) {
			System.out.println(file + " existed!");
		} else {
			String hash = FileHasher.generateFileHash(file);
			if (!hash.equals(fst.getHashCode())) {
				list.add(fst);
			}
		}
		List<FileStructure> children = fst.getChildren();
		if (children != null) {
			for (FileStructure _fst : children) {
				checkMissedFiles(_fst, list);
			}
		}
	}

}
